package cn.demon.pet.service.impl;

import cn.demon.basic.exception.BusinessException;
import cn.demon.basic.query.BaseQuery;
import cn.demon.basic.service.IBaiduAiAuditService;
import cn.demon.basic.util.*;
import cn.demon.order.domain.OrderPetAcquisition;
import cn.demon.order.mapper.OrderPetAcquisitionMapper;
import cn.demon.org.domain.Employee;
import cn.demon.org.domain.Shop;
import cn.demon.org.mapper.EmployeeMapper;
import cn.demon.org.mapper.ShopMapper;
import cn.demon.pet.domain.Pet;
import cn.demon.pet.domain.SearchMasterMsg;
import cn.demon.pet.domain.SearchMasterMsgAuditLog;
import cn.demon.pet.dto.MsgDto;
import cn.demon.pet.mapper.PetMapper;
import cn.demon.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.demon.pet.mapper.SearchMasterMsgMapper;
import cn.demon.pet.query.SearchMasterMsgQuery;
import cn.demon.pet.service.ISearchMasterMsgService;
import cn.demon.basic.service.impl.BaseServiceImpl;
import cn.demon.user.domain.Logininfo;
import cn.demon.user.domain.User;
import cn.demon.user.mapper.LogininfoMapper;
import cn.demon.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {


    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;


    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // 获取登录者信息
        Logininfo logininfo = LoginContext.getLoginUser(request);
        // 通过登录信息id获取user对象
        User user = userMapper.LoadByLogininfoId(logininfo.getId());


        // 1.添加寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        // 2.审核-通过和不通过
        Boolean imgCensorBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        Boolean textCensorBoo = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle() +
                searchMasterMsg.getAddress());
        if (imgCensorBoo && textCensorBoo){
            // 2.1审核通过
            // 2.1.1修改状态
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核通过待商家接单！");

            // 2.1.2获取用户定位
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 计算距离（小于50找到店铺）
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());

            // 2.1.3找到了附近的店铺
            if (nearestShop != null){
                searchMasterMsg.setShopId(nearestShop.getId());
                // 2.1.4模拟发送短信
                System.out.println("您有新的订单，请查看并接单！" + searchMasterMsg.getTitle());
            }

            searchMasterMsgMapper.update(searchMasterMsg);

            // 2.1.5添加日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();

            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setNote("审核通过");
            // 系统审核，所以不需要添加audit_id
            searchMasterMsgAuditLog.setState(1);

            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);

        }else {
            // 2.2审核不通过
            // 2.2.1设置寻主消息
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("有内容违法违规，审核不通过");
            searchMasterMsgMapper.update(searchMasterMsg);

            // 2.2.2添加不通过日志（方便用户寻主消息修改）
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();

            searchMasterMsgAuditLog.setState(0);
            searchMasterMsgAuditLog.setNote("审核不通过，有违规违法内容");
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());

            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
            // 2.2.3不通过给用户提示
            throw new BusinessException("审核不通过，有违规违法内容");


        }
    }

    @Override
    public PageList<SearchMasterMsg> userSearchMasterMsg(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo loginUser = LoginContext.getLoginUser(request);

        User user = userMapper.LoadByLogininfoId(loginUser.getId());
        // 将userId传递到分页参数中，查询想要的信息
        query.setUserId(user.getId());

        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {

        Logininfo loginUser = LoginContext.getLoginUser(request);

        Employee employee = employeeMapper.loadByLogininfoId(loginUser.getId());

        if (employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    @Override
    public void accept(MsgDto msgDto) {

        Long empId = msgDto.getHandler();
        Long msgId = msgDto.getMsgId();
        String note = msgDto.getNote();

        // 创建宠物信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.save(pet);

        // 创建收购订单
        OrderPetAcquisition order =  buildOrder(pet,searchMasterMsg,empId);
        orderPetAcquisitionMapper.save(order);
        // 模拟短信发送
        System.out.println("你有新的订单，请在规定时间内去收购宠物");
    }

    private OrderPetAcquisition buildOrder(Pet pet, SearchMasterMsg msg, Long empId) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getTitle() + "的收购订单");
        //两天之后的此刻就是最后收购时间 - 自动通过定时器取消
        long timeTem = System.currentTimeMillis() + 2*24*60*60*1000;
        order.setLastcomfirmtime(new Date(timeTem));
        order.setState(0);//待处理
        order.setPrice(new BigDecimal(msg.getPrice()));
        //paytype//在处理订单时才处理
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;

    }


    private Pet searchMasterMsg2Pet(SearchMasterMsg msg) {

        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice().toString());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;


    }
}
